package com.zzw.thread.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zzw
 * @see
 * @since 2018/2/13
 */
public class Synchronization {

    private static int resourceCount = 3;
    private static Lock boxLock = new ReentrantLock();
    private static Condition resourceAvailable = boxLock.newCondition();

    public static void main(String[] args) {

        Thread producer = new Thread(() -> {
            try {
                while (true) {
                    producer();
                }
            } catch (InterruptedException e) {}
        });
        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    consumer();
                }
            } catch (InterruptedException e) {}
        });

        producer.start();
        consumer.start();
    }

    public static void producer() throws InterruptedException {
        boxLock.lock();
        resourceCount++;
        resourceAvailable.signalAll();
        System.out.println("Producer: boxSize + 1 = " + resourceCount);
        boxLock.unlock();
        Thread.sleep(1000);
    }

    public static void consumer() throws InterruptedException {
        boxLock.lock();
        try {
            while (resourceCount == 0) {
                resourceAvailable.await();
            }
            resourceCount--;
            System.out.println("Consumer: boxSize - 1 = " + resourceCount);
        }
        finally {
            boxLock.unlock();
        }
        Thread.sleep(500);
    }
}
